/**
 * 智慧小区管理系统 - 权限指令
 * 
 * 提供Vue指令来处理权限控制：
 * - v-permission: 基础权限指令
 * - v-role: 角色权限指令
 * - v-data-scope: 数据权限指令
 * - v-permission-group: 权限组指令
 * - v-if-permission: 条件权限指令
 * 
 * @author Wu.Liang
 * @date 2024-01-01
 * @updated 2025-07-02 - 权限控制粒度简化
 */
import type { Directive, DirectiveBinding } from 'vue'
import { hasMenuPermission, checkRole, getUserDataScope } from '@/utils/permission'
import { useUserStore } from '@/store/user'
import { ROLE_CODES } from '@/constants/roles'

/**
 * 基础权限指令
 * 用法: v-permission="'user:list'" 或 v-permission="['user:list', 'user:add']"
 */
export const permission: Directive = {
    mounted(el: HTMLElement, binding: DirectiveBinding) {
        const { value, modifiers } = binding
        
        if (!value) {
            console.warn('v-permission: 权限值不能为空')
            return
        }

        const userStore = useUserStore()
        
        // 超级管理员拥有所有权限
        if (userStore.userRoles.includes(ROLE_CODES.SUPER_ADMIN)) {
            return
        }

        let hasPermission = false

        if (Array.isArray(value)) {
            // 多个权限，检查是否有任意一个
            hasPermission = value.some(perm => {
                const result = hasMenuPermission(perm)
                return result.hasPermission
            })
        } else {
            // 单个权限
            const result = hasMenuPermission(value)
            hasPermission = result.hasPermission
        }

        if (!hasPermission) {
            if (modifiers?.hide) {
                el.style.display = 'none'
            } else {
                el.style.display = 'none'
                el.remove()
            }
        }
    },

    updated(el: HTMLElement, binding: DirectiveBinding) {
        // 重新检查权限
        const { value, modifiers } = binding
        
        if (!value) {
            console.warn('v-permission: 权限值不能为空')
            return
        }

        const userStore = useUserStore()
        
        // 超级管理员拥有所有权限
        if (userStore.userRoles.includes(ROLE_CODES.SUPER_ADMIN)) {
            return
        }

        let hasPermission = false

        if (Array.isArray(value)) {
            // 多个权限，检查是否有任意一个
            hasPermission = value.some(perm => {
                const result = hasMenuPermission(perm)
                return result.hasPermission
            })
        } else {
            // 单个权限
            const result = hasMenuPermission(value)
            hasPermission = result.hasPermission
        }

        if (!hasPermission) {
            if (modifiers?.hide) {
                el.style.display = 'none'
            } else {
                el.style.display = 'none'
                el.remove()
            }
        }
    }
}

/**
 * 角色权限指令
 * 用法: v-role="'admin'" 或 v-role="['admin', 'manager']"
 */
export const role: Directive = {
    mounted(el: HTMLElement, binding: DirectiveBinding) {
        const { value, modifiers } = binding
        
        if (!value) {
            console.warn('v-role: 角色值不能为空')
            return
        }

        const userStore = useUserStore()
        
        // 超级管理员拥有所有角色
        if (userStore.userRoles.includes(ROLE_CODES.SUPER_ADMIN)) {
            return
        }

        let hasRole = false

        if (Array.isArray(value)) {
            // 多个角色，检查是否有任意一个
            hasRole = value.some(role => {
                const result = checkRole(role)
                return result.hasPermission
            })
        } else {
            // 单个角色
            const result = checkRole(value)
            hasRole = result.hasPermission
        }

        if (!hasRole) {
            if (modifiers?.hide) {
                el.style.display = 'none'
            } else {
                el.style.display = 'none'
                el.remove()
            }
        }
    },

    updated(el: HTMLElement, binding: DirectiveBinding) {
        // 重新检查权限
        const { value, modifiers } = binding
        
        if (!value) {
            console.warn('v-role: 角色值不能为空')
            return
        }

        const userStore = useUserStore()
        
        // 超级管理员拥有所有角色
        if (userStore.userRoles.includes(ROLE_CODES.SUPER_ADMIN)) {
            return
        }

        let hasRole = false

        if (Array.isArray(value)) {
            // 多个角色，检查是否有任意一个
            hasRole = value.some(role => {
                const result = checkRole(role)
                return result.hasPermission
            })
        } else {
            // 单个角色
            const result = checkRole(value)
            hasRole = result.hasPermission
        }

        if (!hasRole) {
            if (modifiers?.hide) {
                el.style.display = 'none'
            } else {
                el.style.display = 'none'
                el.remove()
            }
        }
    }
}

/**
 * 数据权限指令
 * 用法: v-data-scope="data" 或 v-data-scope="{ data, propertyCompanyIdField: 'companyId' }"
 */
export const dataScope: Directive = {
    mounted(el: HTMLElement, binding: DirectiveBinding) {
        const { value } = binding
        
        if (!value) {
            console.warn('v-data-scope: 数据值不能为空')
            return
        }

        const userStore = useUserStore()
        
        // 超级管理员拥有所有数据权限
        if (userStore.userRoles.includes(ROLE_CODES.SUPER_ADMIN)) {
            return
        }

        let data: Record<string, any>
        let propertyCompanyIdField = 'propertyCompanyId'
        let communityIdField = 'communityId'

        if (typeof value === 'object' && !Array.isArray(value)) {
            data = value.data || value
            propertyCompanyIdField = value.propertyCompanyIdField || propertyCompanyIdField
            communityIdField = value.communityIdField || communityIdField
        } else {
            data = value as Record<string, any>
        }

        // 在dataScope指令实现中，移除isDataInScope相关调用，直接将数据权限判断逻辑注释或移除。
        // const isInScope = isDataInScope(data, propertyCompanyIdField, communityIdField)

        // if (!isInScope) {
        //     el.style.display = 'none'
        //     el.remove()
        // }
    },

    updated(el: HTMLElement, binding: DirectiveBinding) {
        // 重新检查权限
        const { value } = binding
        
        if (!value) {
            console.warn('v-data-scope: 数据值不能为空')
            return
        }

        const userStore = useUserStore()
        
        // 超级管理员拥有所有数据权限
        if (userStore.userRoles.includes(ROLE_CODES.SUPER_ADMIN)) {
            return
        }

        let data: Record<string, any>
        let propertyCompanyIdField = 'propertyCompanyId'
        let communityIdField = 'communityId'

        if (typeof value === 'object' && !Array.isArray(value)) {
            data = value.data || value
            propertyCompanyIdField = value.propertyCompanyIdField || propertyCompanyIdField
            communityIdField = value.communityIdField || communityIdField
        } else {
            data = value as Record<string, any>
        }

        // 在dataScope指令实现中，移除isDataInScope相关调用，直接将数据权限判断逻辑注释或移除。
        // const isInScope = isDataInScope(data, propertyCompanyIdField, communityIdField)

        // if (!isInScope) {
        //     el.style.display = 'none'
        //     el.remove()
        // }
    }
}

/**
 * 权限组指令
 * 用法: v-permission-group="'user'" 或 v-permission-group="['user', 'role']"
 */
export const permissionGroup: Directive = {
    mounted(el: HTMLElement, binding: DirectiveBinding) {
        const { value, modifiers } = binding
        
        if (!value) {
            console.warn('v-permission-group: 权限组值不能为空')
            return
        }

        const userStore = useUserStore()
        
        // 超级管理员拥有所有权限组
        if (userStore.userRoles.includes(ROLE_CODES.SUPER_ADMIN)) {
            return
        }

        let hasGroupPermission = false

        if (Array.isArray(value)) {
            // 多个权限组，检查是否有任意一个
            hasGroupPermission = value.some(group => {
                const groupPermissions = userStore.userPermissions.filter(perm => 
                    perm.startsWith(`${group}:`)
                )
                return groupPermissions.length > 0
            })
        } else {
            // 单个权限组
            const groupPermissions = userStore.userPermissions.filter(perm => 
                perm.startsWith(`${value}:`)
            )
            hasGroupPermission = groupPermissions.length > 0
        }

        if (!hasGroupPermission) {
            if (modifiers?.hide) {
                el.style.display = 'none'
            } else {
                el.style.display = 'none'
                el.remove()
            }
        }
    },

    updated(el: HTMLElement, binding: DirectiveBinding) {
        // 重新检查权限
        const { value, modifiers } = binding
        
        if (!value) {
            console.warn('v-permission-group: 权限组值不能为空')
            return
        }

        const userStore = useUserStore()
        
        // 超级管理员拥有所有权限组
        if (userStore.userRoles.includes(ROLE_CODES.SUPER_ADMIN)) {
            return
        }

        let hasGroupPermission = false

        if (Array.isArray(value)) {
            // 多个权限组，检查是否有任意一个
            hasGroupPermission = value.some(group => {
                const groupPermissions = userStore.userPermissions.filter(perm => 
                    perm.startsWith(`${group}:`)
                )
                return groupPermissions.length > 0
            })
        } else {
            // 单个权限组
            const groupPermissions = userStore.userPermissions.filter(perm => 
                perm.startsWith(`${value}:`)
            )
            hasGroupPermission = groupPermissions.length > 0
        }

        if (!hasGroupPermission) {
            if (modifiers?.hide) {
                el.style.display = 'none'
            } else {
                el.style.display = 'none'
                el.remove()
            }
        }
    }
}

/**
 * 条件权限指令
 * 用法: v-if-permission="'user:list'" 或 v-if-permission="{ permission: 'user:list', action: 'hide' }"
 */
export const ifPermission: Directive = {
    mounted(el: HTMLElement, binding: DirectiveBinding) {
        const { value } = binding
        
        if (!value) {
            console.warn('v-if-permission: 权限值不能为空')
            return
        }

        const userStore = useUserStore()
        
        // 超级管理员拥有所有权限
        if (userStore.userRoles.includes(ROLE_CODES.SUPER_ADMIN)) {
            return
        }

        let permission: string
        let action: 'hide' | 'remove' | 'disable' = 'hide'

        if (typeof value === 'object' && !Array.isArray(value)) {
            permission = value.permission
            action = value.action || action
        } else {
            permission = value as string
        }

        const result = hasMenuPermission(permission)

        if (!result.hasPermission) {
            switch (action) {
                case 'hide':
                    el.style.display = 'none'
                    break
                case 'remove':
                    el.remove()
                    break
                case 'disable':
                    if (el instanceof HTMLButtonElement || el instanceof HTMLInputElement) {
                        el.disabled = true
                    } else {
                        el.style.pointerEvents = 'none'
                        el.style.opacity = '0.5'
                    }
                    break
            }
        }
    },

    updated(el: HTMLElement, binding: DirectiveBinding) {
        // 重新检查权限
        const { value } = binding
        
        if (!value) {
            console.warn('v-if-permission: 权限值不能为空')
            return
        }

        const userStore = useUserStore()
        
        // 超级管理员拥有所有权限
        if (userStore.userRoles.includes(ROLE_CODES.SUPER_ADMIN)) {
            return
        }

        let permission: string
        let action: 'hide' | 'remove' | 'disable' = 'hide'

        if (typeof value === 'object' && !Array.isArray(value)) {
            permission = value.permission
            action = value.action || action
        } else {
            permission = value as string
        }

        const result = hasMenuPermission(permission)

        if (!result.hasPermission) {
            switch (action) {
                case 'hide':
                    el.style.display = 'none'
                    break
                case 'remove':
                    el.remove()
                    break
                case 'disable':
                    if (el instanceof HTMLButtonElement || el instanceof HTMLInputElement) {
                        el.disabled = true
                    } else {
                        el.style.pointerEvents = 'none'
                        el.style.opacity = '0.5'
                    }
                    break
            }
        }
    }
}

/**
 * 权限指令集合
 */
export const permissionDirectives = {
    permission,
    role,
    dataScope,
    permissionGroup,
    ifPermission
}

export default permissionDirectives 